package com.yuyou.fn.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.wens.mybatisplus.plugins.Page;
import com.yuyou.fn.arrangement.service.IArrangementService;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.educational.entity.ClassLecture;
import com.yuyou.fn.educational.entity.Room;
import com.yuyou.fn.educational.entity.RoomTime;
import com.yuyou.fn.educational.entity.Teacher;
import com.yuyou.fn.educational.service.*;
import com.yuyou.fn.educational.vo.*;
import com.yuyou.fn.platform.entity.SysUser;
import com.yuyou.fn.platform.permission.DataPermission;
import com.yuyou.fn.report.entity.ClassLectureDetail;
import com.yuyou.fn.report.service.IClassLectureDetailService;
import com.yuyou.fn.report.vo.ClassLectureDetailQueryVo;
import com.yuyou.fn.util.Webs;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by xxx on 2017/3/13
 */

@Controller
@RequestMapping("/api/admin/arrangement")
public class AdminArrangementController extends ApiBaseController {

    @Resource
    private IRoomService roomService;

    @Resource
    private ICourseClassService courseClassService;

    @Resource
    private ITeacherService teacherService;

    @Resource
    private IClassLectureService classLectureService ;

    @Resource
    private IRoomTimeService roomTimeService;

    @Resource
    private IArrangementService arrangementService;

    @Resource
    private IArrangeTeacherHistoryService arrangeTeacherHistoryService;

    @Resource
    private IArrangeLectureHistoryService arrangeLectureHistoryService;

    @Resource
    private IClassLectureDetailService classLectureDetailService;

    @ApiOperation("获取讲次详细列表")
    @RequestMapping(value = "/findClassLectureDetailPage", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<Room>> findClassLectureDetailPage(@RequestParam(value = "periodIds")String periodIds, @RequestParam(value = "busTeamIds",required = false)String busTeamIds, @RequestParam(value = "gradeIds",required = false)String gradeIds, @RequestParam(value = "subjectIds",required = false)String subjectIds, @ModelAttribute ClassLectureDetailQueryVo classLectureDetailQueryVo,@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                                                @RequestParam(value = "pageSize", defaultValue = "20") int pageSize, HttpServletRequest request) {
        classLectureDetailQueryVo.setStatus(1);
        Page<ClassLectureDetail> classLectureDetailPage=classLectureDetailService.findPageByPeriodIds(Utils.toLongIds(periodIds),Utils.toLongIds(busTeamIds),Utils.toLongIds(gradeIds),Utils.toLongIds(subjectIds),classLectureDetailQueryVo,pageNo,pageSize);
        return ReturnResult.success(classLectureDetailPage);
    }

    @ApiOperation("批量调整讲次")
    @RequestMapping(value = "/batchAdjustLectures", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<Room>> batchAdjustLectures(@RequestParam("updateAfterLecture") boolean updateAfterLecture ,@RequestParam("classDate")Date classDate,@RequestParam("classLectureIds")String classLectureIds, HttpServletRequest request) {
        SysUser sysUser=this.getUser(request);
        arrangementService.batchAdjustLectures(Utils.toLongIds(classLectureIds),classDate,updateAfterLecture,sysUser);
        return ReturnResult.success("ok");
    }

    @ApiOperation("批量调整讲次时间")
    @RequestMapping(value = "/batchAdjustLectureTimes", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<Room>> batchAdjustLectureTimes(@RequestParam("classLectureIds")String classLectureIds,@RequestParam("time")String time,  HttpServletRequest request) {
        SysUser sysUser=this.getUser(request);
        arrangementService.batchAdjustLectureTimes(Utils.toLongIds(classLectureIds),time,sysUser);
        return ReturnResult.success("ok");
    }


    @ApiOperation("获取可排教室列表")
    @RequestMapping(value = "/roomListForClassArrangement", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<Room>> roomListForClassArrangement( RoomQueryVo roomQueryVo,@RequestParam("areaTeamId") Long areaTeamId , @RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                                                @RequestParam(value = "pageSize", defaultValue = "20") int pageSize, HttpServletRequest request) {
        Page<Room> page = roomService.findRoomListForClassArrangement(roomQueryVo ,areaTeamId , pageNo, pageSize);
        return ReturnResult.success(page);
    }
    @ApiOperation("获取可排教室列表new")
    @RequestMapping(value = "/roomListForArrangement", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<Room>> roomListForClassArrangement( @RequestParam(value = "classId")long classId,@RequestParam(value = "campusId",required = false)Long campusId,@RequestParam(value = "roomName",required = false)String roomName, @RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                                                 @RequestParam(value = "pageSize", defaultValue = "20") int pageSize, HttpServletRequest request) {
        SysUser sysUser=this.getUser(request);
        Page<Room> page=arrangementService.findRoomByBuyOrCreate(classId,sysUser,campusId,roomName,pageNo,pageSize);
        if (page!=null){
            return ReturnResult.success(page);
        }else {
            Page<Room> newPage = new Page<>(pageNo, pageSize);
            newPage.setTotal(0);
            return ReturnResult.success(newPage);
        }
    }


    @ApiOperation("保存更新班级课室")
    @RequestMapping(value = "/arrangementRoom", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> arrangementRoom(@RequestParam(value = "classId") Long classId, @RequestParam(value = "roomId") Long roomId) {

        courseClassService.saveArrangementRoom(classId, roomId);
        return ReturnResult.success("Ok");
    }

    @ApiOperation("保存更新班级课室new")
    @RequestMapping(value = "/saveOrUpdateArrangementRoom", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> saveOrUpdateArrangementRoom(@RequestParam(value = "classId") Long classId, @RequestParam(value = "roomId") Long roomId,HttpServletRequest request) {
        SysUser sysUser=this.getUser(request);
        arrangementService.saveOrUpdateArrangementRoom(classId,roomId,sysUser);
        return ReturnResult.success("Ok");
    }

    @ApiOperation("释放教室")
    @RequestMapping(value = "/releaseRoom", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> releaseRoom(@RequestParam(value = "classId") Long classId,HttpServletRequest request) {
        arrangementService.releaseRoom(classId);
        return ReturnResult.success("Ok");
    }


    @ApiOperation("获取可排老师列表")
    @RequestMapping(value = "/teacherListForArrangement", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ReturnResult<Page<Teacher>> teacherListForArrangement(@ModelAttribute TeacherQueryVo teacherQueryVo ,
                                                                 @RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                                                 @RequestParam(value = "pageSize", defaultValue = "20") int pageSize, HttpServletRequest request) {
        Page<Teacher> page = teacherService.findTeacherListForClassArrangement(teacherQueryVo , pageNo, pageSize);
        return ReturnResult.success(page);
    }

    @ApiOperation("保存排时间结果")
    @RequestMapping(value = "/saveArrangeClassTimeResult", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> saveArrangeClassTimeResult(@RequestParam("classId") Long classId , @RequestParam("resultJsonStr") String resultJsonStr,HttpServletRequest request) {

        List<ArrangeClassTimeResultVo> arrangeClassTimeResultList = JSONObject.parseObject(resultJsonStr, new TypeReference<List<ArrangeClassTimeResultVo>>() {
        });
        SysUser sysUser=this.getUser(request);
        arrangementService.saveArrangeClassTimeResult(classId, arrangeClassTimeResultList,sysUser );
        return ReturnResult.success("Ok");
    }

    @ApiOperation("讲次列表")
    @RequestMapping(value = "classLectureList", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ReturnResult<List<ClassLecture>> classTimeList(@RequestParam(value = "classId") Long classId) {

        List<ClassLecture> classTimeList = classLectureService.findClassLectureByClassId(classId);
        return ReturnResult.success(classTimeList);
    }

    @ApiOperation("保存更新班级老师")
    @RequestMapping(value = "/arrangeTeacher", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> arrangeTeacher(@RequestParam(value = "classId") Long classId,
                   @RequestParam(value = "teacherIds") String teacherIdsStr, HttpServletRequest request) {
        arrangementService.saveArrangementTeacher(classId, Utils.toLongIds(teacherIdsStr));
        return ReturnResult.success("Ok");
    }

    @ApiOperation("释放老师")
    @RequestMapping(value = "/releaseTeacher", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> releaseTeacher(@RequestParam(value = "classId") Long classId,
                                              HttpServletRequest request) {
        arrangementService.releaseTeacher(classId);
        return ReturnResult.success("Ok");
    }



    @ApiOperation("教室排课情况")
    @RequestMapping(value = "/roomTimeList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public List<Map<String,String>> roomTimeList(@RequestParam(value = "roomId") Long roomId , @RequestParam(value = "start") Date start , @RequestParam(value = "end") Date end, HttpServletRequest request) {
        List<RoomTime> roomTimeList = roomTimeService.findRoomTimeByRoomId(roomId, start, end );
        List<Map<String,String>> retList = new ArrayList<>(roomTimeList.size());
        for(RoomTime roomTime : roomTimeList ){
            Map<String,String> m = new HashMap<>();
            m.put("title",roomTime.getSubject());
            m.put("start", TimeUtils.date2String(roomTime.getStart()));
            m.put("end", TimeUtils.date2String(roomTime.getEnd()));
            retList.add(m);
        }
        return retList;
    }

    @ApiOperation("老师排课情况")
    @RequestMapping(value = "/teacherClassLectureList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public List<Map<String,String>> teacherClassLectureList(@RequestParam(value = "teacherId") Long teacherId , @RequestParam(value = "start") Date start , @RequestParam(value = "end") Date end, HttpServletRequest request) {
        if(end != null ){
            end = DateUtils.addDays(end,1);
        }
        List<ClassLecture> classTimeList = classLectureService.findClassLectureByTeacherId(teacherId, start, end);
        List<Map<String,String>> retList = new ArrayList<>(classTimeList.size());
        for(ClassLecture classTime : classTimeList ){
            Map<String,String> m = new HashMap<>();
            m.put("title","");
            String date = TimeUtils.date2String(classTime.getClassDate(),"yyyy-MM-dd ");
            m.put("start", date + classTime.getStartTime());
            m.put("end", date + classTime.getEndTime() );
            retList.add(m);
        }
        return retList;
    }


    @ApiOperation("重排")
    @RequestMapping(value = "/prepareRearrange", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> prepareRearrange(@RequestParam("classId")Long classId , @RequestParam("which") Integer which ) {
        //courseClassService.prepareRearrange(classId,which);
        arrangementService.confirmRearrange(classId,which);
        return ReturnResult.success("Ok");
    }


    @ApiOperation("重排时间")
    @RequestMapping(value = "/rearrangeTimeForLecture", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> rearrangeTimeForLecture( @RequestParam("classLectureId")Long classLectureId , @RequestParam("date") String date ,@RequestParam("time") String time , @RequestParam("updateAfterLecture") boolean updateAfterLecture ,HttpServletRequest request ) {

        SysUser sysUser=this.getUser(request);
        arrangementService.rearrangeTimeForLecture(classLectureId,date,time,updateAfterLecture,sysUser);
        return ReturnResult.success("Ok");
    }

    @ApiOperation("单讲排老师")
    @RequestMapping(value = "/rearrangeTeacherForLecture", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> rearrangeTeacherForLecture(@RequestParam("remark")String remark,
                                                         @RequestParam("classLectureId")Long classLectureId ,
                                                         @RequestParam("teacherId")Long teacherId ,
                                                         @RequestParam("updateAfterLecture") boolean updateAfterLecture,
                                                         @RequestParam("useInFollowingLectrue") boolean useInFollowingLectrue ) {
        if (useInFollowingLectrue){
            courseClassService.reArrangeTeacherForLectures(classLectureId,teacherId,remark);
        }else{
            courseClassService.rearrangeTeacherForLecture(classLectureId,teacherId ,updateAfterLecture,remark );
        }
        return ReturnResult.success("Ok");
    }

    @ApiOperation("教师临调情况")
    @RequestMapping(value = "/findArrageTeacherHistoryPage", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> findArrageTeacherHistoryPage(ArrangeTeacherHistoryQueryVo arrangeTeacherHistoryQueryVo, @RequestParam(value = "pageNo") int pageNo,@RequestParam(value = "pageSize") int pageSize,HttpServletRequest request) {
        DataPermission dataPermission=this.getDataPermission(request);

        if (arrangeTeacherHistoryQueryVo.getEndDate()!=null){
            arrangeTeacherHistoryQueryVo.setEndDate(TimeUtils.changeOneDateLastTime(arrangeTeacherHistoryQueryVo.getEndDate()));
        }
        Page<ArrangeTeacherHistoryDetailVo> page=arrangeTeacherHistoryService.findArrageTeacherHistoryPage(dataPermission,arrangeTeacherHistoryQueryVo,pageNo,pageSize);
        return ReturnResult.success(page);
    }

    @ApiOperation("导出教师临调情况")
    @RequestMapping(value = "/exportArrageTeacherHistory",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> exportArrageTeacherHistory(ArrangeTeacherHistoryQueryVo arrangeTeacherHistoryQueryVo,HttpServletRequest request, HttpServletResponse response) throws Exception{
        DataPermission dataPermission=this.getDataPermission(request);
        if (arrangeTeacherHistoryQueryVo.getEndDate()!=null){
            arrangeTeacherHistoryQueryVo.setEndDate(TimeUtils.changeOneDateLastTime(arrangeTeacherHistoryQueryVo.getEndDate()));
        }
        Webs.writeExcel(request,response, arrangeTeacherHistoryService.exportArrageTeacherHistory( dataPermission, arrangeTeacherHistoryQueryVo), "教师临调情况");
        return ReturnResult.success("ok");
    }


    @ApiOperation("上课时间调整记录")
    @RequestMapping(value = "/findArrangeLectureHistoryPage", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<ArrangeLectureHistoryDetailVo>> findArrangeLectureHistoryPage(@ModelAttribute ArrangeLectureHistoryQueryVo arrangeLectureHistoryQueryVo, @RequestParam(value = "pageNo") int pageNo,@RequestParam(value = "pageSize") int pageSize,HttpServletRequest request) {
        DataPermission dataPermission=this.getDataPermission(request);

        if (arrangeLectureHistoryQueryVo.getEndDate()!=null){
            arrangeLectureHistoryQueryVo.setEndDate(TimeUtils.changeOneDateLastTime(arrangeLectureHistoryQueryVo.getEndDate()));
        }
        Page<ArrangeLectureHistoryDetailVo> page=arrangeLectureHistoryService.findArrangeLectureHistoryPage(dataPermission,arrangeLectureHistoryQueryVo,pageNo,pageSize);
        return ReturnResult.success(page);
    }

    @ApiOperation("导出上课时间调整记录")
    @RequestMapping(value = "/exportArrangeLectureHistory",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> exportArrangeLectureHistory(@ModelAttribute ArrangeLectureHistoryQueryVo arrangeLectureHistoryQueryVo,HttpServletRequest request, HttpServletResponse response) throws Exception{
        DataPermission dataPermission=this.getDataPermission(request);
        if (arrangeLectureHistoryQueryVo.getEndDate()!=null){
            arrangeLectureHistoryQueryVo.setEndDate(TimeUtils.changeOneDateLastTime(arrangeLectureHistoryQueryVo.getEndDate()));
        }
        Webs.writeExcel(request,response, arrangeLectureHistoryService.exportArrangeLectureHistory( dataPermission, arrangeLectureHistoryQueryVo), "上课时间调整记录");
        return ReturnResult.success("ok");
    }
}